package com.example.fruitdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.fruitdemo.mapper.AddressMapper;
import com.example.fruitdemo.pojo.Address;
import com.example.fruitdemo.pojo.User;
import com.example.fruitdemo.ruslet.R;
import com.example.fruitdemo.service.AddressService;
import com.example.fruitdemo.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {
   @Autowired
   private UserService userService;
    @Override
    public R<Address> getByAuth(String authorization) {
        Long userid = userService.getidByAuth(authorization);
        LambdaQueryWrapper<Address> addressWrapper=new LambdaQueryWrapper<>();
        addressWrapper.eq(Address::getUserid,userid).eq(Address::getStatus,1);
        Address address = this.getOne(addressWrapper);
        return R.Ok(address);
    }

    @Override
    public Long getidByName(String receiver) {
         LambdaQueryWrapper<Address> addressWrapper=new LambdaQueryWrapper<>();
         addressWrapper.eq(Address::getAccepter,receiver);
        Address one = this.getOne(addressWrapper);
        return one.getId();
    }

    @Override
    public R<Address> subaddress(Address address) {
        //先查询是否有该地址
        Long userid = address.getUserid();
        address.setStatus(1);
        LambdaQueryWrapper<Address> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getUserid,userid);
        if( this.getOne(queryWrapper)==null){
            //没有改地址，新增一个
            this.save(address);
            return R.Ok(this.getOne(queryWrapper));
        }else {
            //不为空，删除在新增
            Address one = this.getOne(queryWrapper);
            boolean b = this.removeById(one.getId());
            if(b==true){
                this.save(address);
                return R.Ok( this.getOne(queryWrapper));
            }else{
                return R.Err("修改失败！");
            }

        }

    }
}
